package com.szj.coroutine.project

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.szj.coroutine.project.jvm.util.NetWorkApi
import com.szj.coroutine.project.jvm.util.printlnJob
import com.szj.coroutine.project.jvm.util.printlnThread
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.test.setMain
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import kotlin.concurrent.thread
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlin.system.measureTimeMillis

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        val scope = MainScope()
//        scope.launch {
//            Log.i("szjCoroutine:", "main -- thread:${Thread.currentThread().name}")
//            launch(Dispatchers.IO) {
//                launch {
//                    launch {
//                        withContext(Dispatchers.Main) {
//                            Log.i(
//                                "szjCoroutine",
//                                "launch4 -- thread:${Thread.currentThread().name}"
//                            )
//                        }
//                    }
//                }
//            }
//        }

        // todo ================全局异常测试===========


//        val scope = CoroutineScope(Dispatchers.IO)
//
//        scope.launch {
//
//            Log.i("测试", "${5 / 0}")
//        }


        // todo =========================================

//        val useTime = measureTimeMillis {
//
//            runBlocking<Unit> {
//                printlnThread("main start") // TODO 代码1
//
//                val job = launch {
//                    printlnThread("launch 1") // TODO 代码3
//                }
//
//                val job2 = launch {
//                    printlnThread("launch 2") // TODO 代码4
//                }
//
//                printlnJob("job1 = ", job)
//                printlnJob("job2 = ", job2)
//
//                printlnThread("main end") // TODO 代码2
//            }
//        }
//
//        println("runBlocking 执行时间为:$useTime")


        // todo =========================================
//        val channel = Channel<String>(
//            capacity = 50,
//            onBufferOverflow = BufferOverflow.SUSPEND
//        )
//
//        runBlocking {
//            println("main start")
//            launch() {
//                println("launch 1 start")
//                delay(1000)
//                channel.trySend("我是延迟1s后的数据 1")
//                channel.trySend("我是延迟1s后的数据 2")
//                channel.trySend("我是延迟1s后的数据 3")
////                channel.send("我是延迟1s后的数据 1")
////                channel.send("我是延迟1s后的数据 2")
////                channel.send("我是延迟1s后的数据 3")
//                println("launch 1 end")
//            }
//
//            println("main mid")
//            launch {
//                println("launch 2 start")
//                println("result: ${channel.receive()}\t")
//                println("launch 2 end")
//            }
//            println("main end")
//        }

//        test2()

        lifecycleScope.launch {
            test3()
        }

    }

    private suspend fun testSCC() = suspendCancellableCoroutine<String> {
        it.resume("恢复了")
        it.invokeOnCancellation {
            println("close")
        }
        GlobalScope.launch {
            delay(1000)
            println("异步操作完成")
        }
    }

    private fun test3() = runBlocking<Unit> {
        println("main start")
        val job = launch {
            testSCC()
        }
        delay(100)
        job.cancel() // 取消协程
        println("main end")
    }

//
//    // TODO ============== 使用 suspendCancellableCoroutine2 写法 ==============
//    private suspend fun test3() {
//        val coroutineScope = CoroutineScope(Dispatchers.Main)
//        val deferred = coroutineScope.async {
//            requestNetWorkData3()
//        }
//        val result = runCatching {
//            deferred.await()
//        }
//        result.onSuccess {
//            printlnThread("返回正确结果为:$it")
//        }.onFailure {
//            printlnThread("请求失败错误为:${it.message}")
//        }
//    }


    // region test2

    /*
     * 作者: 史大拿
     * 时间: 2023/2/22 11:07
     * TODO:
     */
    private fun requestLoginNetworkData(
        account: String, pwd: String, result: Result<String>.() -> Unit
    ) {
        if (account == "123456789" && pwd == "666666") {
            result.invoke(Result.success("123"))
        } else {
            result.invoke(Result.failure(RuntimeException("登陆失败")))
        }
    }

    private fun test2() {
        thread { // 开启一个线程
            requestLoginNetworkData("987654321", "123456") {
                // 切换线程
                runOnUiThread {
                    // 数据监听
                    onSuccess {
                        printlnThread("登陆成功 :$it")
                    }.onFailure {
                        printlnThread("登陆失败 :${it.message}")
                    }
                }
            }

        }
    }
    // endregion

}